import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Form, Card, Input, Select, Icon, Button, message, Tree, Spin } from "antd";
import { getLastPermission } from "../../../utils/role";


const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;

function fn(data, pid) {
  let result = [], temp;
  if(data && pid){
    for (let i in data) {
      if (data[i].parentId == pid) {
        result.push(data[i]);
        temp = fn(data, data[i].menuId);
        if (temp.length > 0) {
          data[i].children = temp;
        }
      }
    }
  }
  return result;
}

Array.prototype.ToTreeJson = function (pid) {
  let result = [], temp;
  for (let i in this) {
    if (this[i].parentId == pid) {
      result.push(this[i]);
      temp = fn(this, this[i].menuId);
      if (temp.length > 0) {
        this[i].children = temp;
      }
    }
  }
  return result;
}

const treeData = data =>{
  return data.map(item=>{
    if(item.children){
      return {children:treeData(item.children),key:`${item.menuId}`, name:item.name};
    }else{
      return {key:`${item.menuId}`, name:item.name};
    }
  })
}


@connect(({ role }) => ({
  loading:role.loading,
  detaildata:role.detaildata,
  permissionMap:treeData(role.permissionMap.ToTreeJson(0)),
}))
@Form.create()
export default class NoticeAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.detailInfoId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
    this.state={
      treeSelect:[],
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;


    dispatch({
      type: "role/fetch_permission_map"
    }).then(()=>{
      if (this.detailInfoId!==0) {
        // 编辑时 读取详情
        dispatch({
          type: "role/fetch_role_info",
          payload: {
            roleId: this.detailInfoId
          }
        }).then(()=>{
          this.setState({
            treeSelect:this.props.detaildata.menuIdList
          })
        })
      }
    });

  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const action = this.detailInfoId!=0 ? 'edit' : 'add';
        const roleId = this.detailInfoId!=0 ? this.detailInfoId : undefined;

        // if(values.taskTime){
        //   values.beginTime = values.taskTime[0].unix() * 1000;
        //   values.endTime = values.taskTime[1].unix() * 1000;
        // }

        dispatch({
          type: `role/${action}_role`,
          payload: {
            ...values,
            roleId,
          }
        }).then(() => {
            this.handleReset();
            message.success(this.detailInfoId!=0 ? "角色信息已修改" : "角色信息已添加");
            if(this.detailInfoId!=0){
              this.goBack();
            }else{
              router.push(`/system/role/list`);
            }
        });
      }
    });
  }

  handleReset = () => {
    const { detaildata } = this.props;
    this.setState({
      treeSelect: this.detailInfoId === 0 ? [] : detaildata.menuIdList
    });
    this.props.form.resetFields();
  };


  goBack = () => {
    const { dispatch, location } = this.props;
    router.push({ pathname:`/system/role/list`,  query: { ...location.query} });
  }


  getTreeCheck = (checkedKeys, e) => {
    this.setState({
      treeSelect:checkedKeys,
    })
    const { permissionMap } = this.props;
    // console.log('aaa',getLastPermission(permissionMap, checkedKeys,'deptId'));
    this.props.form.setFieldsValue({
      // role_authority:[...checkedKeys,...e.halfCheckedKeys],
      menuIdList: getLastPermission(permissionMap, checkedKeys)
    });

  };

  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.key} />;
    });
  };



  render() {
    const { loading, detaildata, permissionMap } = this.props;
    const { treeSelect } = this.state;
    const { getFieldDecorator } = this.props.form;

    // console.log('permissionMap',permissionMap)

    return (
       <Card
             bodyStyle={{padding:'50px 100px'}}
       >
         {loading.info && this.detailInfoId!==0  &&  <div className={"globalSpin"}><Spin tip="信息加载中，请稍后..."/></div>}
         {
           ((!loading.info && this.detailInfoId!==0) || this.detailInfoId===0) &&
           <Form layout="horizontal">
             <Row gutter={24}>
               <Col span={8}>
                 <FormItem label="角色名称">
                   {getFieldDecorator("roleName", {
                     initialValue: this.detailInfoId === 0 ? undefined : detaildata.roleName,
                     rules: [
                       {
                         required: true,
                         message: "角色名称"
                       }
                     ]
                   })(<Input placeholder="角色名称"/>)}
                 </FormItem>
               </Col>

               <Col span={16}>
                 <FormItem label="角色说明">
                   {getFieldDecorator("remark", {
                     initialValue: this.detailInfoId === 0 ? undefined : detaildata.remark,
                     rules: [
                       {
                         // required: true,
                         message: "请输入用户名"
                       }
                     ]
                   })(<Input placeholder="请输入角色说明"/>)}
                 </FormItem>
               </Col>
             </Row>

             <Row gutter={24}>
               <Col span={24} style={{ padding: 30 }}>
                 <FormItem label="权限设置" colon={false}>
                   {getFieldDecorator("menuIdList", {
                     initialValue: this.detailInfoId === 0 ? undefined : detaildata.menuIdList,
                     rules: [{ required: true, message: "请选择用户权限" }]
                   })(<Input type="hidden"/>)}
                   <Fragment>
                     {
                       (!permissionMap || permissionMap.length == 0) &&
                       <span><Spin/>权限加载中，请稍后...</span>
                     }
                     {
                       permissionMap && permissionMap.length > 0 &&
                       <Tree
                         checkable
                         defaultExpandAll={true}
                         onCheck={this.getTreeCheck}
                         // defaultCheckedKeys={detaildata.menuIdList && permissionMap ? getLastPermission(permissionMap, detaildata.menuIdList) : []}
                         checkedKeys={treeSelect}
                       >
                         {this.renderTreeNodes(permissionMap)}
                       </Tree>

                     }
                   </Fragment>
                 </FormItem>
               </Col>
             </Row>

             <Row gutter={24}>
               <Col span={24} style={{ textAlign: 'center', padding: 30 }}>
                 <Button
                   onClick={this.handleFormSubmit.bind(this)}
                   type="primary"
                   size="large"
                   style={{ marginRight: 15 }}
                   loading={loading.add}
                 >
                   提交
                 </Button>
                 <Button
                   onClick={this.handleReset.bind(this)}
                   type="default"
                   size="large"
                 >
                   重置
                 </Button>
               </Col>
             </Row>
           </Form>

         }

       </Card>
    );
  }
}
